package _17_剑指Offer;

import com.sun.org.apache.bcel.internal.generic.NEW;

public class _50_剑指Offer第一个只出现一次的字符 {

    public static void main(String[] args) {

        _50_剑指Offer第一个只出现一次的字符 v = new _50_剑指Offer第一个只出现一次的字符();

        String str = "leetcode";
        System.out.println(v.firstUniqChar(str));
    }

    // Api调用法则
    public char firstUniqChar(String s) {
        int len = s.length();
        int max = len;
        for (int i = 'a'; i <= 'z'; i++) {
            int st = s.indexOf(i);
            if (st != - 1 && st == s.lastIndexOf(i) && st < max) max = st;
        }
        return max == len? ' ': s.charAt(max);
    }

    // 使用数组计数法
    public char firstUniqChar1(String s) {
        int[][] ins = new int[26][2];

        int len = s.length();

        for (int i = 0; i < len; i++) {
            int curChar = s.charAt(i);
            ins[curChar - 'a'][0]++;
            ins[curChar - 'a'][1] = i;
        }

        int index = len;
        for (int[] in : ins) {
            if (in[0] == 1 && in[1] < index) index = in[1];
        }
        return index == len? ' ': s.charAt(index);
    }

}
